#!/bin/sh
# Copyright (c) 2011, bkil.hu
# This program is free software and can be distributed under the terms of
# the GNU General Public License v2,
# see COPYING for detailed licensing terms.

# created on 2011-04-14

# /etc/sudoers:
# %ifupdown ALL = NOPASSWD: /sbin/ifup eth0, /sbin/ifdown eth0

main(){
 local ROUTER=`get_router_addr`
 echo "test server: $ROUTER" >&2
 local MIND=5
 local D=$MIND
 while true
 do
  if
   ping -q -c 1 -w 1 $ROUTER > /dev/null
  then
   D=$MIND
   sleep 1
  else
   echo "reconnect attempt" >&2
   date >&2
   sudo ifdown eth0

   sleep 0.1 #not required
   sudo ifup eth0 #not needed if you have ifplugd

   sleep $D
   D=`expr $D \* 2`
   echo "done" >&2
  fi
 done
}

get_router_addr(){
 local ROUTERIDX=1
 /sbin/ifconfig eth0 |
 grep "inet addr" |
 sed "s~^.*inet addr:\([0-9]*\.[0-9]*\.[0-9]*\.\).*$~\1${ROUTERIDX}~"
}

main "$@"
